<template>
  <div class="tpl-container">
    <div class="mb20">
      <span class="color_494949 ft12 pr5">{{ translate('订单编码') }}：</span>
      <ElInput
        v-model="eslCode"
        class="w164 mr14"
        :placeholder="translate('请输入订单编码')"
      />
      <ElButton class="settingBtn" type="primary" @click="search">
        {{ translate('查询') }}
      </ElButton>
    </div>
    <div class="table">
      <ElTable v-loading="loading" :border="true" :data="tableData">
        <ElTableColumn
          :label="translate('订单编码')"
          prop="out_trade_no"
          width="auto"
        />
        <ElTableColumn label="商品" :show-overflow-tooltip="true" width="300">
          <template #default="{ row }">
            <div
              v-for="(item, index) in row.Remark"
              :key="index"
              class="switch"
            >
              <div class="inline-block">
                <img
                  class="suspend"
                  height="50"
                  :src="item.goods_img"
                  width="50"
                />
              </div>
              <div
                class="inline-block ft12 ml10 h-50"
                style="width: 64%; vertical-align: top"
              >
                <p>{{ item.goods_name }}</p>
                <p>
                  <span>单价：{{ item.unit_price }}</span>
                  &nbsp;
                  <span>数量：{{ item.quantity }}</span>
                </p>
              </div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('商品数量')"
          prop="SortCode"
          width="auto"
        />
        <ElTableColumn
          :label="translate('订单金额(元)')"
          prop="amount"
          width="auto"
        />
        <ElTableColumn
          :label="translate('创建时间')"
          prop="CreateDate"
          width="auto"
        />
        <ElTableColumn align="center" :label="translate('状态')" width="auto">
          <template #default="{ row }">
            <div>
              {{ row.trade_state_desc ? row.trade_state_desc : '未支付' }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn align="center" :label="translate('收货人')" width="auto">
          <template #default="{ row }">
            <div v-if="row.uaddressjson">
              {{ row.uaddressjson.consignee }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          align="center"
          :label="translate('手机号码')"
          width="auto"
        >
          <template #default="{ row }">
            <div v-if="row.uaddressjson">
              {{ row.uaddressjson.mobile }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          align="center"
          :label="translate('收货地址')"
          width="auto"
        >
          <template #default="{ row }">
            <div v-if="row.uaddressjson">
              {{
                (row.uaddressjson.province ? row.uaddressjson.province : '') +
                (row.uaddressjson.city ? row.uaddressjson.city : '') +
                row.uaddressjson.address
                  ? row.uaddressjson.address
                  : '' +
                    (row.uaddressjson.adNumber ? row.uaddressjson.adNumber : '')
              }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('操作')" width="200">
          <template #default="{ row }">
            <ElButton link type="primary" @click="editFn(row)">
              {{ translate('录入快递号') }}
            </ElButton>
            <ElButton
              v-if="row.orefundsstatus === '1'"
              link
              type="danger"
              @click="refundFn(row)"
            >
              {{ translate('退款审核') }}
            </ElButton>
            <ElButton
              v-if="row.orefundsstatus === '0' && row.trade_state === 'SUCCESS'"
              link
              type="danger"
              @click="sysrefundFn(row)"
            >
              {{ translate('发起退款') }}
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :before-close="handleClose"
      :title="title"
      width="30%"
    >
      <div class="table">
        <el-form label-position="left" label-width="100px">
          <el-form-item :label="translate('快递编码')">
            <el-input v-model="tracktype" style="width: 350px" />
          </el-form-item>
          <el-form-item :label="translate('快递单号')">
            <el-input v-model="trackno" style="width: 350px" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">{{ translate('取消') }}</el-button>
          <el-button type="primary" @click="confirm">
            {{ translate('确定') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { MenuAuth } from '~/src/utils/permission'
  import {
    OrderGetPageData,
    wxcreaterefund,
    createorderrefunds,
    wxeditreceivestatus,
  } from '@/api/mupro'
  import router from '@/router'
  import { useEleStore } from '@/store/modules/coms'
  import { translate } from '@/i18n'
  const eslCode = ref('')
  const eslName = ref('')
  const lcdType = ref('')
  const tracktype = ref('')
  const trackno = ref('')
  const selectInfo = ref({})
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 20,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"out_trade_no","value":${eslCode.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const dialogVisible = ref(false)
  const loading = ref(false)
  const { clearWidgets, clearEditorData } = useEleStore()
  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const total = ref(0)
  // 获取表格数据
  const editFn = (val: any) => {
    console.log(val)
    tracktype.value = ''
    trackno.value = ''
    dialogVisible.value = true
    selectInfo.value = val
  }
  const handleClose = () => {
    dialogVisible.value = false
  }
  const gettableData = async () => {
    loading.value = true
    const { data } = await OrderGetPageData(searchInfo)
    loading.value = false
    tableData.value = data?.rows || []
    if (tableData.value) {
      tableData.value.map((item) => {
        if (item.Remark) {
          item.Remark = JSON.parse(item.Remark)
          item.uaddressjson = JSON.parse(item.uaddressjson)
        }
        if (item.orefundsjson) {
          item.orefundsjson = JSON.parse(item.orefundsjson)
        }
      })
      console.log(tableData.value)
    }
    total.value = data?.total || 0
  }
  gettableData()
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  const confirm = async () => {
    const params = {
      out_trade_no: selectInfo.value.out_trade_no,
      openid: selectInfo.value.openid,
      tracktype: tracktype.value,
      trackno: trackno.value,
    }
    const data = await wxeditreceivestatus(params)
    // ElMessage.success(data.message)
    dialogVisible.value = false
    gettableData()
  }
  const refundFn = async (val: any) => {
    if (val.orefundsjson.status === '"PROCESSING"') {
      ElMessage.warning('退款申请中')
      return
    }
    $baseConfirm(translate('你确定同意用户退款吗？'), null, async () => {
      const params = {
        transaction_id: val.transaction_id,
        out_refund_no: val.orefundsjson.out_refund_no,
        total: val.amount,
        refund: val.amount,
      }
      const data = await wxcreaterefund(params)
      ElMessage.success(data.message)
      gettableData()
    })
  }
  const sysrefundFn = async (val: any) => {
    $baseConfirm(translate('你确定给用户发起退款吗？'), null, async () => {
      const params = {
        transaction_id: val.transaction_id,
        openid: val.openid,
        out_trade_no: val.out_trade_no,
      }
      const data = await createorderrefunds(params)
      if (data.code === '200') {
        data.data.amount = val.amount
        wxrefund(data.data)
      }
    })
  }
  const wxrefund = async (val: any) => {
    const params = {
      transaction_id: val.transaction_id,
      out_refund_no: val.out_refund_no,
      total: val.amount,
      refund: val.amount,
    }
    const data = await wxcreaterefund(params)
    if (data.status === 'PROCESSING') {
      ElMessage.success('退款中')
      gettableData()
    }
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }

  const search = () => {
    searchInfo.pageNo = 1
    if (
      eslCode.value.trim() !== '' ||
      eslName.value.trim() !== '' ||
      lcdType.value.trim() !== ''
    ) {
      const arr = []
      eslCode.value.trim() !== '' &&
        arr.push({
          name: 'out_trade_no',
          value: eslCode.value,
          displayType: 'like',
        })
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.wheres = `[{"name":"out_trade_no","value": '',"displayType":"like"}]`
    }
    gettableData()
  }
  const $baseConfirm = inject('$baseConfirm') as any
  const deleteFn = async (row: any) => {
    $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
      await delCstemp({
        id: row.ID,
      })
      gettableData()
    })
  }
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
    }

    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr14 {
      margin-right: 14px;
    }

    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }
  }
  .tpl-container .switch {
    min-width: 170px !important;
  }
  .inline-block {
    display: inline-block;
  }
  .ft12 {
    font-size: 12px;
  }
  .ml10 {
    margin-left: 10px;
  }
  .h-50 {
    vertical-align: top;
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
</style>
